package com.xneure.code.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResourceTree {
	private Object _data;
	private char _key = 0;
	private ResourceTree parent;
	private Map<Character, ResourceTree> children;

	public ResourceTree(ResourceTree resourceTree) {
		parent = resourceTree;
	}

	public void put(char[] key, Object data) {
		put(0, key, data);
	}

	protected void put(int index, char[] key, Object data) {
		if (0 == _key) {
			_key = key[index];
		}
		if (index == key.length - 1) {
			_data = data;
			return;
		}
		ResourceTree obj;
		if (null == children) {
			children = new HashMap<Character, ResourceTree>(10);
		}
		obj = children.get(key[++index]);
		if (null == obj) {
			obj = new ResourceTree(this);
			children.put(key[index], obj);
		}
		obj.put(index, key, data);
	}

	public Object getData(String key) {
		return getData(0, key.toCharArray());
	}

	protected Object getData(int index, char[] charArray) {
		if (_key == charArray[index]) {
			if (index == charArray.length - 1) {
				return _data;
			}
		}
		if (children != null) {
			ResourceTree obj = children.get(charArray[++index]);
			if (null != obj) {
				return obj.getData(index, charArray);
			}
		}
		return null;
	}

	public Object getData() {
		return _data;
	}

	public char getKey() {
		return _key;
	}

	public ResourceTree getParent() {
		return parent;
	}

	public List<ResourceTree> getChildren() {
		return new ArrayList<ResourceTree>(children.values());
	}

}
